<template>
  <div id="call-rescue">
    <div v-if="rescueList && rescueList.length > 0">
      <div v-for="(item, index) in rescueList" :key="index" class="item">
        <div class="logo">
          <img :src="item.logo" alt="">
        </div>
        <div class="info" v-tap="{methods: showMap, item:item}">
          <span class="title" v-if="item.title">{{item.title}}</span>
          <span class="address" v-if="item.address">{{`地址:${item.address}`}}</span>
          <span class="number" v-if="item.number">{{`电话:${item.number}`}}</span>
        </div>
        <div class="call-icon">
          <span v-if="item.distance || item.distance == 'NaN'">{{`${item.distance}公里`}}</span>
          <a :href="`tel:${item.number}`">
            <i class="iconfont">&#xe6f4;</i>
          </a>
        </div>
      </div>
    </div>
    <empty v-if="showEmpty" message="当前位置没有救援机构"></empty>
  </div>
</template>

<script>
import callMap from "./call_map"
import empty from 'components/empty-page.vue'
// services
import {
  OneKeyRescue,
  WechatService,
  LocationService
} from "services/rescue/call.js"
// images
import default_icon from "assets/APP-icon_80.png"
export default {
  name: "call-rescue",
  components: { callMap, empty },
  data() {
    return {
      // resources
      default_icon,
      // model-view
      rescueList: [],
      showEmpty: false,
      point: "", // 用于计算距离 (当前位置)
      shopPoint: "" // 用于地图展示 (救援机构位置)
    }
  },
  mounted() {
    let vm = this;
    // @TODO @TEST @DELETE test 后面删除
    getLoc().then(function (point) {
      vm.point = new BMap.Point(point.longitude, point.latitude);
      // @TODO @TEST @DELETE 
      vm.getRescueList('吉林省');
    })

    // 1. 获取省份和点坐标的方法 使用微信内置接口获取位置信息
    // WechatService.initWechatConfig(this, WechatService.initWechatReq(this));
    // LocationService.invokeWechatReq(this).then(province => {
    //   // 2. 获取救援机构列表
    //   this.getRescueList(province);
    // })
  },
  methods: {
    // 电话救援，获取救援机构列表
    getRescueList(province) {
      this.$.carId && OneKeyRescue.bind(this)(this.getOneKeyRescueRequest(province), res => {
        console.log(res)
        // res 是否返回经纬度
        if (res.latitude && res.longitude) {
          this.point = new BMap.Point(res.longitude, res.latitude);
        }

        // 官方救援电话信息
        if (res.rescueDatas && res.rescueDatas.length > 0) {
          res.rescueDatas.forEach(item => {
            this.rescueList.push({
              title: item.brand,
              logo: (item.brandLogo && this.addPath(item.brandLogo)) || this.default_icon,
              address: '',
              number: item.officialPhoneNumber
            })
          })
        }

        // 4s店救援信息列表
        if (res.shopRescueInfos && res.shopRescueInfos.length > 0) {
          res.shopRescueInfos.forEach(item => {
            this.rescueList.push({
              title: item.name,
              logo: (item.brandLogo && this.addPath(item.brandLogo)) || this.default_icon,
              address: item.address,
              number: item.mobile,
              point: {
                lng: item.longitude,
                lat: item.latitude
              }
            })
          })
        }

        // 省份救援信息
        if (res.provinceName && res.provincePhoneNumber) {
          this.rescueList.push({
            title: res.provinceName,
            logo: this.default_icon,
            address: '',
            number: res.provincePhoneNumber,
            distance: ''
          })
        }

        this.rescueList && this.getDistance()

        if (this.rescueList.length == 0 ) {
          this.showEmpty = true
        }
      })
    },
    // get request
    getOneKeyRescueRequest(province) {
      // clientType	string	客户端类型。[0安卓、1苹果、2web、3微信]
      // methodName	string	方法名(后台区分请求标识)
      // shopId	string	店铺ID
      // userId	string	用户ID
      // carId	string	车辆ID
      // provinceName	string	车辆位置（省份）
      return {
        carId: this.$.carId,
        provinceName: province
      }
    },
    // 计算距离信息
    getDistance() {
      let vm = this;
      let _rescueList = JSON.parse(JSON.stringify(this.rescueList));
      this.rescueList = [];
      _rescueList.forEach(item => {
        // 是否重复
        let hasNoRepeat = vm.rescueList.every(function (_item) {
          return item.number !== _item.number;
        });

        // 计算距离
        if (item.point) {
          let mapTmp = new BMap.Map('mapTmp');
          item.distance = (Math.round(mapTmp.getDistance(vm.point, new BMap.Point(item.point.lng, item.point.lat)) / 100) / 10).toFixed(0);
        }

        if (hasNoRepeat) {
          vm.rescueList.push(item);
        }
      })
    },
    showMap(params) {
      let item = params.item;
      if (item.point) {
        // 展示地图
        this.shopPoint = item.point
        this.$router.push({
          name: "callMap",
          query: {
            point: JSON.stringify(this.shopPoint),
            item: JSON.stringify(item)
          }
        })
      }
    }
  }
}
// @TODO @TEST @DELETE 后面删除
function getLoc(vm) {
  return new Promise(function (resolve, reject) {
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
      if (geolocation.getStatus() == BMAP_STATUS_SUCCESS) {
        resolve({ longitude: r.point.lng, latitude: r.point.lat })
        console.log("您的位置：" + r.point.lng + "," + r.point.lat, r);
      } else {
        console.log("failed" + this.getStatus());
      }
    });
  })
}
</script>

<style lang="scss" scoped>
#call-rescue {
  .item {
    display: flex;
    justify-content: space-between;
    align-items: stretch;
    position: relative;
    &:after {
      content: " ";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 0;
      border-bottom: 1px solid #929292;
      transform: scaleY(0.4);
    }
    > div {
      padding: 10px;
    }
    .logo {
      img {
        width: 60px;
        height: 60px;
      }
    }
    .info {
      width: 100%;
      display: flex;
      flex-direction: column;
      color: #707070;
      padding: 10px 0;
      span {
        line-height: 20px;
      }
      .title {
        color: #000;
        font-size: 14px;
      }
    }
    .call-icon {
      align-self: center;
      width: 60px;
      color: #707070;
      >span {
        word-break: keep-all;
      }
      .iconfont {
        color: #707070;
        font-size: 25px;
        line-height: 40px;
      }
    }
  }
}
</style>
